﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Data;
using System.Reflection;
using Newtonsoft.Json;

namespace Suk.Common
{ 
    /// <summary>
    /// Json帮助类
    /// </summary>
    public class JsonHelper
    {
        private static void InitSetting()
        {
            Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {    //日期类型默认格式化处理
                setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //空值处理
                setting.NullValueHandling = NullValueHandling.Ignore;

                return setting;
            });
        }

        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeObject(object o)
        {
            InitSetting();
            string json = JsonConvert.SerializeObject(o);
            return json.Replace("0001/1/1 0:00:00", "");//去除空日期 0001/1/1 0:00:00
        }
        public static object DeserializeObject(string o)
        {
            InitSetting();
            return JsonConvert.DeserializeObject(o);
        }
        public static object DeserializeObject(string o, Type type)
        {
            InitSetting();
            return JsonConvert.DeserializeObject(o, type);
        }

        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>对象实体</returns>
        public static T DeserializeObject<T>(string json) where T : class
        {
            InitSetting();
            object o = JsonConvert.DeserializeObject(json, typeof(T));
            T t = o as T;
            return t;
        }

    }



}
